<?php

/*
$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);

$fp = fopen('file.csv', 'w');

foreach ($list as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);
*/
	set_include_path('../140dev/db');
	
	require_once('140dev_config.php');	  
	require_once('db_lib.php');

	ob_start();

    function query_to_csv($oDB, $query, $filename, $attachment = false, $headers = true) {
        

        if($attachment) {
            // send response headers to the browser
            header( 'Content-Type: text/csv' );
            header( 'Content-Disposition: attachment;filename='.$filename);
            $fp = fopen('php://output', 'w');
        } else {
            $fp = fopen($filename, 'w');
        }
        
        if(!$oDB)
  		{
  			die('Could not connect: ' . mysql_error());
  		}
  		$result = $oDB->select($query);
        
        
        if($headers) {
            $list = array('Id', 'Name', 'Address', 'Url', 'Email','Facebook','Twitter','Id Trip', 'Id Atrapalo', 'Id Tenedor', 'Id Restalo', 'Id Salir', 'Id Yelp');
            fputcsv($fp, $list);
        }
        
        while($row = mysqli_fetch_row($result)) {
            fputcsv($fp, $row);
        }
        
        fclose($fp);
    }

    // Using the function
    $sql = "SELECT T1.ID_RESTAURANT, T1.DS_REST_NAME, T1.DS_REST_ADDRESS, T1.DS_REST_URL, T1.DS_REST_EMAIL, T1.DS_REST_FACEBOOK, T1.DS_REST_TWITTER, ";
	$sql = $sql . "T2.ID_REST_SOURCE as ID_REST_TRIPADVISOR, T3.ID_REST_SOURCE as ID_REST_ATRAPALO, ";
	$sql = $sql . "T4.ID_REST_SOURCE as ID_REST_TENEDOR, T5.ID_REST_SOURCE as ID_REST_RESTALO, T6.ID_REST_SOURCE as ID_REST_SALIR, T7.ID_REST_SOURCE as ID_REST_YELP ";
	$sql = $sql . "FROM MAST_RESTAURANTS T1 ";
	$sql = $sql . "LEFT JOIN MAST_REST_TRIPADVISOR T2 ON T1.ID_RESTAURANT = T2.ID_RESTAURANT ";
	$sql = $sql . "LEFT JOIN MAST_REST_ATRAPALO T3 ON T1.ID_RESTAURANT = T3.ID_RESTAURANT ";
	$sql = $sql . "LEFT JOIN MAST_REST_TENEDOR T4 ON T1.ID_RESTAURANT = T4.ID_RESTAURANT ";
	$sql = $sql . "LEFT JOIN MAST_REST_RESTALO T5 ON T1.ID_RESTAURANT = T5.ID_RESTAURANT ";
	$sql = $sql . "LEFT JOIN MAST_REST_SALIR T6 ON T1.ID_RESTAURANT = T6.ID_RESTAURANT ";
	$sql = $sql . "LEFT JOIN MAST_REST_YELP T7 ON T1.ID_RESTAURANT = T7.ID_RESTAURANT ";
	$sql = $sql . "WHERE T1.BL_ACTIVE ='Y' ";
	$sql = $sql . "ORDER BY T1.ID_RESTAURANT ASC ";
    // $db_conn should be a valid db handle
	$oDB = new db;

    // output as an attachment
    query_to_csv($oDB, $sql, "matching.csv", true);

    // output to file system
    //query_to_csv($db_conn, $sql, "test.csv", false);
?>